package io.bdmc.core.msp2000.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.bdmc.common.utils.ByteUtil;
import io.bdmc.modules.bss.entity.DeviceMachineOsw;
import io.bdmc.modules.bss.service.IDeviceMachineOswService;
import io.bdmc.core.msp2000.DataBuild;
import io.bdmc.core.msp2000.DataParse;
import io.bdmc.core.msp2000.model.Msp2000Ter2Platform;
import io.bdmc.core.msp2000.SetMsgResponse;
import io.bdmc.core.udp.UdpClientSendData;

@Component
public class OswDeviceUtil {
    @Autowired
    IDeviceMachineOswService oswService;

    @Autowired
    UdpClientSendData udpClient;

    protected static Logger logger = LoggerFactory.getLogger(OswDeviceUtil.class);

    /**
     * 给osw 设备发送 参数设置
     * 
     * @param diskSn  单盘sn
     * @param channel 通道
     * @param ip      ip
     * @param port    端口
     * @return 是否发送成功
     */
    public boolean setOswConfig(String diskSn, String channel, String ip, int port) {
        try {
            final DeviceMachineOsw osw = oswService
                    .getOne(new QueryWrapper<DeviceMachineOsw>().eq("disk_sn", diskSn).last("limit 1"));
            osw.setChannelState(channel + "");
            String Msg = DataBuild.buildSetOSW(diskSn, 1, osw);
            String parseData = udpClient.sendPollCommand(ip, port, Msg.toLowerCase());

            if(parseData.length()==0){
                logger.error("setOswConfig失败重新设置一次");
                parseData = udpClient.sendPollCommand(ip, port, Msg.toLowerCase());
            }
            
            Msp2000Ter2Platform msg = DataParse.parseAllMsg(ByteUtil.hexToBytes(parseData));
            SetMsgResponse setMsgResponse = DataParse.parseSetResponse(msg.getData());
            logger.info("设置光开关：" + Msg.toLowerCase() + "设置结果：" + setMsgResponse.isOswSetOK() + ","
                    + setMsgResponse.getCmdData());
            return setMsgResponse.isOswSetOK();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            logger.error(ex.getCause().getMessage());
        }
        return false;
    }
}
